<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/26
 * Time: 14:26
 */

namespace app\common;


use app\common\model\Trade;
use app\common\model\Users;
use think\Log;

class PaySuccess
{
    static $payment_type = "";

    static function setPaymentType($payment_type)
    {
        self::$payment_type = $payment_type;
    }

    static function do_()
    {
        $code = input("code");
        $trade = Trade::get(["code" => $code]);
        if ($trade->is_pay) {
            Log::error(sprintf('"交易号 %s 已支付', $code));
            return false;
        }
        if (!(self::$payment_type)) {
            Log::error(sprintf('self::$payment_type 未设置 ，清先调用 setPaymentType 设置交易方式 '));
            return false;
        }
        if (!($trade instanceof Trade)) {
            Log::error(sprintf("交易号 %s 未找到实质交易", $code));
            return false;
        }
        switch ($trade->trade_type) {
            case Trade::TRADE_SHOP:
                self::trade_shop($trade);
                break;
            case Trade::TRADE_RECHARGE:
                self::trade_recharge($trade);
                break;
            default:
                Log::error(sprintf("交易号 %s 未定义交易类型", $code));
                return false;
        }
        return true;;
    }

    /**
     * 购物付款
     * @param Trade $trade
     */
    static function trade_shop(Trade $trade)
    {
        $order_list = $trade->getOrders();
        /**
         * 余额支付  扣除余额
         */
        if (self::$payment_type == Trade::PAYMENT_YUE) {
            /** @var Users $user */
            $user = Users::get(["id" => $trade->user_id]);
            $fund = $user->getUserFund();
            $yue = $fund->value;
            $money = $trade->value;
            if ($money > 0) {
                $money = 0 - $money;
            }
            if ($yue + $money <= 0) {
                response_json(Code::YU_E_BUZU);
            }
            $fund->setInc("value", $money);
        }
        /**
         * @var  $k
         * @var \app\common\model\Order $order
         */
        foreach ($order_list as $k => $order) {
            OrderStatus::yizhifu($order);
        }
        $trade->pay_success(self::$payment_type);
    }

    /**
     * 充值付款
     * @param Trade $trade
     */
    static function trade_recharge(Trade $trade)
    {
        $money = $trade->value;
        /** @var Users $user */
        $user = Users::get(["id" => $trade->user_id]);
        if ($money > 0) {
            $fund = $user->getUserFund();
            $fund->setInc("value", $money);
        }
        $trade->pay_success(self::$payment_type);
    }

}